package chasegame;

import java.awt.Point;
import java.util.ArrayList;

import org.newdawn.slick.Color;

import game.GameMap;
import game.MovableGameObject;

public class Chaser extends MovableGameObject {
	private double angle = 0;
	private double movespeed;
	private Point startPos;
	private Color color;

	public Chaser(int x, int y) {
		super(x, y);
		startPos = new Point(x,y);
		this.setWidth(32);
		this.setHeight(32);
		movespeed = (Math.random())+1.5;
		color = new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255));
	}
	
	@Override
	public String curImgPath(){
		return "res/frog.png";
	}
	
	@Override
	public void move(GameMap gameMap){
		if(canMoveWithoutGoingOutOfMap(gameMap.getWidth(), gameMap.getHeight())){
			this.addCoordinates((int)this.getXSpeed(),(int)this.getYSpeed());
		}
	}
	
	public double getAngle(){
		return this.angle;
	}
	
	public Color getColor(){
		return color;
	}

	public void chase(GameMap gameMap){
		Point lastpoint = getClosestCoordinates(gameMap);

		int x = lastpoint.x;
		int y = lastpoint.y;
		
		angle = (Math.atan2(y - getY(), x - getX()) * 180 / Math.PI);
		
		this.setXSpeed(movespeed*Math.cos(Math.toRadians(angle)));
		this.setYSpeed(movespeed*Math.sin(Math.toRadians(angle)));
	}
	
	private Point getClosestCoordinates(GameMap gameMap){
		int mapW2 = gameMap.getWidth()*2;
		int mapH2 = gameMap.getHeight()*2;
		Point pt1 = new Point(mapW2, mapH2);
		Point pt2 = new Point(mapW2, mapH2);
		Point pt3 = new Point(mapW2, mapH2);
		Point pt4 = new Point(mapW2, mapH2);
		
		for(int x = getX(); x < gameMap.getWidth(); x++){
			for(int y = getY(); y < gameMap.getHeight(); y++){
				if(gameMap.hasPointAtLocation(x, y)){
					pt1 = new Point(x,y);
					break;
				}
			}
			for(int y = getY(); y > 0; y--){
				if(gameMap.hasPointAtLocation(x, y)){
					pt2 = new Point(x,y);
					break;
				}
			}
		}
		
		for(int x = getX(); x > 0; x--){
			for(int y = getY(); y < gameMap.getHeight(); y++){
				if(gameMap.hasPointAtLocation(x, y)){
					pt3 = new Point(x,y);
					break;
				}
			}
			for(int y = getY(); y > 0; y--){
				if(gameMap.hasPointAtLocation(x, y)){
					pt4 = new Point(x,y);
					break;
				}
			}
		}
		Point cp = getClosestPoint(pt1, pt2, pt3, pt4);
		if(cp.x > gameMap.getWidth() || cp.y > gameMap.getHeight()){
			return startPos;
		}else{
			return cp;
		}
	}
	
	private Point getClosestPoint(Point p1, Point p2, Point p3, Point p4){
		Point curLoc = new Point(this.getX(), this.getY());
		double d1,d2,d3,d4;
		d1 = curLoc.distance(p1);
		d2 = curLoc.distance(p2);
		d3 = curLoc.distance(p3);
		d4 = curLoc.distance(p4);
		
		if(d1 < d2 && d1 < d3 && d1 < d4){
			return p1;
		}
		if(d2 < d1 && d2 < d3 && d2 < d4){
			return p2;
		}
		if(d3 < d1 && d3 < d2 && d3 < d4){
			return p3;
		}
		else{
			return p4;
		}
	}
}
